<template>
  <!-- 处方组成表单弹窗 -->
  <el-dialog
    v-model="dialog.visible"
    :title="dialog.title"
    width="800px"
    @close="handleCloseDialog"
  >
    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['project:compose:add']" type="success" @click="handleOpenDialog()">
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['project:compose:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column key="drug" label="中药饮片名" prop="drug" min-width="150" align="center" />
        <el-table-column
          key="method"
          label="炮制方法"
          prop="method"
          min-width="150"
          align="center"
        />
        <el-table-column key="gram" label="克或份量" prop="gram" min-width="150" align="center" />

        <el-table-column
          key="symptom"
          label="对证加味"
          prop="symptom"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="forSyndrome"
          label="药性"
          prop="forSyndrome"
          min-width="150"
          align="center"
        />
      </el-table>
    </el-card>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit()">确定</el-button>
        <el-button @click="handleCloseDialog()">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
defineOptions({
  name: "Compose",
  inheritAttrs: false,
});

import ComposeAPI, { ComposePageVO, ComposeForm, ComposePageQuery } from "@/api/project/compose";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<ComposePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 处方组成表格数据
const pageData = ref<ComposePageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 处方组成表单数据
const formData = reactive<ComposeForm>({});

// 处方组成表单校验规则
const rules = reactive({
  tcmId: [{ required: true, message: "请输入处方ID", trigger: "blur" }],
  externalForm: [{ required: true, message: "请输入干湿生熟", trigger: "blur" }],
  drug: [{ required: true, message: "请输入中药饮片名", trigger: "blur" }],
  method: [{ required: true, message: "请输入炮制方法", trigger: "blur" }],
  gram: [{ required: true, message: "请输入克或份量", trigger: "blur" }],
  weightUnit: [{ required: true, message: "请输入计量单位", trigger: "blur" }],
  symptom: [{ required: true, message: "请输入对证加味", trigger: "blur" }],
  forSyndrome: [{ required: true, message: "请输入药性", trigger: "blur" }],
});

/** 查询处方组成 */
function handleQuery(id?: number) {
  loading.value = true;
  queryParams.tcmId = id;

  ComposeAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置处方组成查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开处方组成弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改处方组成";
    ComposeAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增处方组成";
  }
}

/** 提交处方组成表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        ComposeAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ComposeAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭处方组成弹窗 */
function handleCloseDialog() {
  dialog.visible = false;

  formData.id = undefined;
}

/** 删除处方组成 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ComposeAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 接收公告详情
const openDetail = async (id: number) => {
  dialog.title = "查看详情";
  dialog.visible = true;
  handleQuery(id);
};

defineExpose({
  openDetail,
});
</script>
